package com.sky.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.sky.constant.MessageConstant;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.exception.BaseException;
import com.sky.mapper.CategoryMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Override
    public PageResult selectCategoryPage(CategoryPageQueryDTO dto) {
        Integer page = dto.getPage();
        Integer pageSize = dto.getPageSize();
        if (ObjectUtil.isNull( page) || ObjectUtil.isNull(pageSize)){
            throw new BaseException(MessageConstant.PAGE_PARAM_NO_NULL);
        }
        String name = dto.getName();
        Integer type = dto.getType();
        Math.max(page,1);
        Math.max(pageSize,5);

        Page<Category> categoryPage = new Page<>(page, pageSize);
        lambdaQuery().like(ObjectUtil.isNotEmpty(name),Category::getName,name)
                .eq(ObjectUtil.isNotEmpty(type),Category::getType,type)
                .orderByAsc(Category::getSort)
                .page(categoryPage);
        return PageResult.builder().total(categoryPage.getTotal()).records(categoryPage.getRecords()).build();
    }

    @Override
    public void removeCategoryById(Long id) {
        Category category = getById(id);
        if (ObjectUtil.isEmpty( category)){
            throw new RuntimeException(MessageConstant.CATEGORY_NOT_FOUND);
        }
        //当前分类关联了套餐，则不能删除
        List<Setmeal> list = Db.lambdaQuery(Setmeal.class)
                               .eq(Setmeal::getCategoryId, id)
                               .list();
        if (CollUtil.isNotEmpty(list)){
            throw new BaseException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }
        //当前分类关联了菜品，则不能删除
        List<Dish> list1 = Db.lambdaQuery(Dish.class)
                             .eq(Dish::getCategoryId, id)
                              .list();
        if (CollUtil.isNotEmpty(list1)){
            throw new BaseException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }
        removeById(id);

    }
}
